import 'dart:convert';
import 'package:audioplayers/audioplayers.dart';
import 'package:free_music_player/constants/api_constants.dart';
import 'package:free_music_player/models/song_model.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

class MusicService {
  final AudioPlayer _audioPlayer = AudioPlayer();
  SongModel? _currentSong;
  List<SongModel> _playlist = [];
  int _currentIndex = -1;
  int _playMode = AppConstants.playModeSequence;
  List<int> _history = [];
  bool _isPlaying = false;

  // 获取当前播放状态
  bool get isPlaying => _isPlaying;

  // 获取当前歌曲
  SongModel? get currentSong => _currentSong;

  // 获取播放列表
  List<SongModel> get playlist => _playlist;

  // 获取当前索引
  int get currentIndex => _currentIndex;

  // 获取播放模式
  int get playMode => _playMode;

  // 获取历史记录
  List<int> get history => _history;

  // 初始化服务
  Future<void> init() async {
    await loadHistory();
    _audioPlayer.onPlayerComplete.listen((_) {
      nextSong();
    });
  }

  // 搜索歌曲
  Future<List<SongModel>> searchSongs(String keyword) async {
    try {
      final response = await http.get(Uri.parse('${ApiConstants.search}?keywords=$keyword'));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        final result = data['result'];
        if (result != null && result['songs'] != null) {
          List<SongModel> songs = [];
          for (var songJson in result['songs']) {
            // 获取歌曲详情
            SongModel song = await getSongDetail(songJson['id']);
            songs.add(song);
          }
          return songs;
        }
      }
      return [];
    } catch (e) {
      print('搜索歌曲失败: $e');
      return [];
    }
  }

  // 获取歌曲详情
  Future<SongModel> getSongDetail(int songId) async {
    try {
      final response = await http.get(Uri.parse('${ApiConstants.songDetail}?ids=$songId'));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['songs'] != null && data['songs'].isNotEmpty) {
          // 获取歌曲URL
          final urlResponse = await http.get(Uri.parse('${ApiConstants.songUrl}?id=$songId'));
          if (urlResponse.statusCode == 200) {
            final urlData = json.decode(urlResponse.body);
            if (urlData['data'] != null && urlData['data'].isNotEmpty) {
              String? mp3Url = urlData['data'][0]['url'];
              SongModel song = SongModel.fromJson(data['songs'][0]);
              // 创建一个新的SongModel实例，包含mp3Url
              return SongModel(
                id: song.id,
                name: song.name,
                artists: song.artists,
                album: song.album,
                duration: song.duration,
                mp3Url: mp3Url,
              );
            }
          }
          return SongModel.fromJson(data['songs'][0]);
        }
      }
      throw Exception('获取歌曲详情失败');
    } catch (e) {
      print('获取歌曲详情失败: $e');
      throw e;
    }
  }

  // 获取歌词
  Future<String> getLyric(int songId) async {
    try {
      final response = await http.get(Uri.parse('${ApiConstants.lyric}?id=$songId'));
      if (response.statusCode == 200) {
        final data = json.decode(response.body);
        if (data['lrc'] != null && data['lrc']['lyric'] != null) {
          return data['lrc']['lyric'];
        }
      }
      return '暂无歌词';
    } catch (e) {
      print('获取歌词失败: $e');
      return '获取歌词失败';
    }
  }

  // 设置播放列表并播放
  Future<void> setPlaylistAndPlay(List<SongModel> playlist, int index) async {
    if (playlist.isEmpty || index < 0 || index >= playlist.length) return;

    _playlist = playlist;
    _currentIndex = index;
    _currentSong = playlist[index];
    await playCurrentSong();
  }

  // 播放当前歌曲
  Future<void> playCurrentSong() async {
    if (_currentSong == null || _currentSong!.mp3Url == null) return;

    try {
      await _audioPlayer.play(UrlSource(_currentSong!.mp3Url!));
      _isPlaying = true;
      // 添加到历史记录
      addToHistory(_currentSong!.id);
    } catch (e) {
      print('播放失败: $e');
      _isPlaying = false;
    }
  }

  // 暂停播放
  Future<void> pause() async {
    await _audioPlayer.pause();
    _isPlaying = false;
  }

  // 继续播放
  Future<void> resume() async {
    await _audioPlayer.resume();
    _isPlaying = true;
  }

  // 下一首
  Future<void> nextSong() async {
    if (_playlist.isEmpty) return;

    switch (_playMode) {
      case AppConstants.playModeSequence:
        _currentIndex = (_currentIndex + 1) % _playlist.length;
        break;
      case AppConstants.playModeRandom:
        _currentIndex = DateTime.now().millisecondsSinceEpoch % _playlist.length;
        break;
      case AppConstants.playModeSingleLoop:
        // 单曲循环，索引不变
        break;
    }

    _currentSong = _playlist[_currentIndex];
    await playCurrentSong();
  }

  // 上一首
  Future<void> previousSong() async {
    if (_playlist.isEmpty) return;

    switch (_playMode) {
      case AppConstants.playModeSequence:
        _currentIndex = (_currentIndex - 1 + _playlist.length) % _playlist.length;
        break;
      case AppConstants.playModeRandom:
        _currentIndex = DateTime.now().millisecondsSinceEpoch % _playlist.length;
        break;
      case AppConstants.playModeSingleLoop:
        // 单曲循环，索引不变
        break;
    }

    _currentSong = _playlist[_currentIndex];
    await playCurrentSong();
  }

  // 切换播放模式
  void togglePlayMode() {
    _playMode = (_playMode + 1) % 3;
  }

  // 添加到历史记录
  Future<void> addToHistory(int songId) async {
    // 避免重复添加
    if (_history.contains(songId)) {
      _history.remove(songId);
    }
    _history.insert(0, songId);
    // 限制历史记录数量
    if (_history.length > AppConstants.maxHistoryCount) {
      _history = _history.sublist(0, AppConstants.maxHistoryCount);
    }
    // 保存历史记录
    await saveHistory();
  }

  // 保存历史记录
  Future<void> saveHistory() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setStringList('history', _history.map((id) => id.toString()).toList());
  }

  // 加载历史记录
  Future<void> loadHistory() async {
    final prefs = await SharedPreferences.getInstance();
    final historyList = prefs.getStringList('history') ?? [];
    _history = historyList.map((id) => int.parse(id)).toList();
  }

  // 清除历史记录
  Future<void> clearHistory() async {
    _history = [];
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove('history');
  }

  // 释放资源
  void dispose() {
    _audioPlayer.dispose();
  }
}